extends Node
var a=0

@onready var credits_layer = $CreditsLayer
@onready var scroll_text = $CreditsLayer/ScrollText
@onready var btn_back = $CreditsLayer/Btn_Back

@onready var ending_bgm = $EndingBGM

func _ready() -> void:
	if get_tree().paused:
		get_tree().paused = false
	
	VN_SystemUI.show_hud() #显示HUD
	
	if VN_SystemUI.pending_load_slot != "":
		print("检测到跨场景读档请求...")
		
		await get_tree().process_frame
		
		Dialogic.Save.load(VN_SystemUI.pending_load_slot)
		VN_SystemUI.pending_load_slot = ""
		
		#读档后，立刻刷新一次按钮状态
		VN_SystemUI.update_drink_menu_visibility()
		
	else:
		#正常开局
		print("正常开局")
		
		#强制把酒单功能锁上
		Dialogic.VAR.set_variable("HUD.drink_menu_unlocked", false)
		
		#根据刚刚锁上的状态，强制刷新UI
		VN_SystemUI.update_drink_menu_visibility()

		Dialogic.start("character2_4")
	
	Dialogic.signal_event.connect(_on_dialogic_signal)
	
	credits_layer.visible = false
	Dialogic.start("character2_4") # 你的结局Timeline
	
	ending_bgm.play()
	
	
	
	
#func _on_dialogic_signal(arg: String):
	#if arg == "end_game":
		#print("游戏通关，准备跳转制作人员名单...")
		#
		#VN_SystemUI.auto_play_credits = true
		#
		#VN_SystemUI.hide_hud()
		#
		#Dialogic.clear()
		#await get_tree().process_frame
		#
		##SceneLoader.change_scene_with_grid_spread("res://scene/MainMenu.tscn")
		#get_tree().change_scene_to_file("res://scene/MainMenu.tscn")

func _on_dialogic_signal(arg: String):
	if arg == "end_game":
		print("触发结局，开始播放名单...")
		play_credits_sequence()



func play_credits_sequence():
	#隐藏UI
	if is_instance_valid(VN_SystemUI):
		VN_SystemUI.hide_hud()
		VN_SystemUI.force_hide_drink_menu()
	
	#把返回键藏起来
	if btn_back: btn_back.visible = false
	
	#显示黑色背景层
	credits_layer.visible = true
	

	var text_content = "[center]"
	text_content += "[font_size=128]THE END[/font_size]\n\n\n\n\n"
	
	text_content += "[font_size=96]XJTLUBI SOFT[/font_size]\n\n\n"
	
	text_content += "[font_size=64]"
	
	text_content += "成员名单\n\n\n"
	text_content += "Abao\n\n"
	text_content += "Kansal-Hagen\n\n"
	text_content += "Lanmao\n\n"
	text_content += "pppig\n\n"
	text_content += "彦澄\n\n\n\n\n\n"

	text_content += "非常感谢游玩我们的游戏！！！\n\n\n\n\n\n\n"
	
	text_content += "2025卡赢杯参赛作品\n\n\n"
	text_content += "[font_size=96]the Bridge of Forgetfulness[/font_size]\n\n"
	
	text_content += "[/font_size][/center]"
	
	scroll_text.text = text_content
	#准备滚动动画
	var screen_height = get_viewport().get_visible_rect().size.y
	scroll_text.position.y = screen_height + 1100
	
	#计算终点
	var end_pos_y = -scroll_text.size.y - 50 
	
	#创建动画
	var tween = create_tween()
	
	#设置滚动时间
	tween.tween_property(scroll_text, "position:y", end_pos_y, 25.0).set_trans(Tween.TRANS_LINEAR)
	
	#动画结束后，自动跳转回主菜单
	tween.tween_callback(_return_to_main_menu)

# 跳转函数
func _return_to_main_menu():
	print("结局播放完毕，返回主菜单")
	
	var audio_tween = create_tween()
	audio_tween.tween_property(ending_bgm, "volume_db", -80.0, 2.0)
	
	await audio_tween.finished
	
	#彻底清理 Dialogic (包括停止音乐)
	Dialogic.clear()
	
	# 切换场景
	get_tree().change_scene_to_file("res://scene/MainMenu.tscn")
